package mx.com.mindbits.bandpay;


import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import mx.com.mindbits.bandpay.dao.ContactsDAO;
import mx.com.mindbits.bandpay.utils.ConstantsValues;
import mx.com.mindbits.bandpay.utils.GPSTracker;
import mx.com.mindbits.bandpay.utils.Utils;
import mx.com.mindbits.bandpay.vo.TAECompraVO;
import mx.com.mindbits.dao.contacts;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class PayServiceActivity extends SherlockActivity {
	
	private EditText campoMonto;
	private EditText campoExtra;
	private TextView campoTotal;
	private TextView descripcion;
	private Intent activityChange;
	private Bundle bundle;
	private TAECompraVO compra;		
	private float monto;
	private float extra;
	private float total;
	private GPSTracker gps;
	private double longitude;
	private double latitude;
	private Context  context;
	private ActionBar actionBar;
	private int position_dot;
	private int position_dot_extra;
	
	private Menu menu;
	private MenuItem itemMenuClean;
	private MenuItem itemMenuSend;
	private Button btClean;
	private Button btSend;
	
	private boolean flagMonto=true;
	private boolean flagExtra =true;
	
	
	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}
	
	
	public float getMonto() {
		return monto;
	}

	public void setMonto(float monto) {
		this.monto = monto;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}
	
	
	//View _continuar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay_service);
		longitude = 0;
		latitude = 0;
		monto = 0;
		extra = 0;
		position_dot = 0;
		position_dot_extra = 0;
		setContext( getBaseContext() );
		
		/////////////////////action bar ///////////////
		actionBar = getSupportActionBar();
		actionBar.setTitle("");
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);		
		
		//////////////////////////////////////////////
		
		campoMonto = (EditText) findViewById(R.id.editMount);
		campoExtra = (EditText)findViewById(R.id.editExtra);
		campoTotal = (TextView)findViewById(R.id.editTotal);
		descripcion = (TextView)findViewById(R.id.editDescripcion);
				
		compra  = new TAECompraVO();
		gps = new GPSTracker(this);
		
		campoMonto.setHint(R.string.hint_monto);
		campoMonto.requestFocus();
		campoExtra.setHint(R.string.hint_extras);
		descripcion.setHint(R.string.text_descripcionDummy);
		
		campoExtra.setImeOptions(EditorInfo.IME_ACTION_NEXT);
		campoExtra.setImeOptions(EditorInfo.IME_ACTION_SEND);
		
		campoExtra.setOnEditorActionListener(new OnEditorActionListener(){
			
			@Override
			public boolean onEditorAction(TextView arg0, int action, KeyEvent arg2) {
				
				// TODO Auto-generated method stub
				if(action == EditorInfo.IME_ACTION_SEND){
					Log.i("teclas", "e"+descripcion.getText().toString());
					if(descripcion.getText().toString().isEmpty()){
						showAlertDescriptionEmpty();
						Log.i("teclas", "e" + arg2);
					}
					
					return true;
				}
				
				return false;
			}
			
		});
		
		final InputFilter filterExtra = new InputFilter(){

			@Override
			public CharSequence filter(CharSequence arg0, int st, int ed,
					Spanned arg3, int dst, int ded) {				
				for(int i = 0; i < arg3.length(); i++){
				    	if(arg3.charAt(i) == '.' ){
				    			position_dot_extra = i;
				    			break;
						}//end if
				    }
				
				if(position_dot_extra > 0){
					if(arg0.equals(".")){
						if(flagExtra){
							campoExtra.setSelection(position_dot_extra + 1);
							campoExtra.getText().replace(position_dot_extra+1, position_dot_extra+3, "");
							flagExtra=false;
						}
					}		
					
				}
				
				if(ded <= position_dot_extra){
					return null;
				}
				
				if((arg3.length()-position_dot_extra) > 2){
					return "";
				}
				
				return null;
			}
			
		};
		
		campoExtra.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {}
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if(campoExtra.getText().toString().equals(".") ){
					campoExtra.setText("0.");
					campoExtra.setSelection(2);
					flagExtra=true;
							
				}
				if(!campoExtra.getText().toString().isEmpty()){
					campoExtra.setFilters(new InputFilter[]{filterExtra});
					
					if(campoExtra.length() == 1){
						campoExtra.setText(campoExtra.getText().toString() + ".00");
						campoExtra.setSelection(1);
						flagExtra=true;
					}

					extra = Float.parseFloat(campoExtra.getText().toString());
					
				}else{
					extra = 0;
					campoExtra.setHint(R.string.hint_extras);
				}
				total = getMonto() + extra;
				campoTotal.setText( Utils.setFloatFormat(total));
				//campoTotal.setText(Float.toString(total));
			}
			
		});
		
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		setMenu( menu );
		getSupportMenuInflater().inflate(R.menu.activity_pay_service, menu);

		itemMenuSend = (MenuItem) menu.findItem(R.id.sendPay);
		itemMenuClean = (MenuItem) menu.findItem(R.id.cleanForm);
		btSend = (Button) itemMenuSend.getActionView().findViewById(R.id.buttonGeneric);
		
		if(campoMonto.getText().toString().isEmpty()){
			btSend.setBackgroundResource(R.drawable.button_disable_shape);
			btSend.setText(R.string.label_buttonbar_send);
			btSend.setEnabled(false);
		}else{
			//btSend = (Button) itemMenuSend.getActionView().findViewById(R.id.buttonGeneric);
			btSend.setBackgroundResource(R.drawable.blue_button_shape);
			btSend.setText(R.string.label_buttonbar_send);
			btSend.setEnabled(true);
		}
		
		
		btClean = (Button) itemMenuClean.getActionView().findViewById(R.id.buttonGeneric);
		btClean.setBackgroundResource(R.drawable.blue_button_shape);
		btClean.setText(R.string.form_cleanButton);
		btClean.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setCleanForm();
				
			}
			
		});
		
		btSend.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendPayOption();
			}
			
		});
		return true;
	}
	
	
	
	
	@Override 
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case android.R.id.home:
			Intent intent = new Intent(this, MainMenuActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		/*case R.id.sendPay:												
			sendPayOption();
			break;			
		case R.id.cleanForm:
			setCleanForm();
			break;*/
		default:
			break;
		}
		return false;		
	}
	
	@Override
	public void onResume(){
		super.onResume();	
				
		final InputFilter filter = new InputFilter(){

			@Override
			public CharSequence filter(CharSequence arg0, int start, int end,
					Spanned arg3, int dst, int dend) {				
				for(int i = 0; i < arg3.length(); i++){
				    if(arg3.charAt(i) == '.'){
				    			position_dot = i;
				    			break;
						}//end if
					}
				if(position_dot>0){
					if(arg0.equals(".") ){
						if(flagMonto){
							campoMonto.setSelection( position_dot + 1 );
		    				campoMonto.getText().replace((dend+1), (dend + 3), "");
		    				flagMonto=false;
						}
					}
					
					if(dend <= position_dot){
						return null;
					}
					
					if((arg3.length()-position_dot) > 2){
						return "";
					}
					
				}
				return null;
			}
			
		};
		
		
		
		campoMonto.addTextChangedListener(new TextWatcher(){

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

				
				if(campoMonto.getText().toString().equals("0.00") ||
						campoMonto.getText().toString().equals("0.0")	||
						campoMonto.getText().toString().equals("0") ||
						campoMonto.getText().toString().equals(".00") || 
						(Float.parseFloat(campoMonto.getText().toString()) == 0)){
						btSend.setBackgroundResource(R.drawable.button_disable_shape);//
						flagMonto = true;
						btSend.setEnabled(false);
					}else{
						btSend.setBackgroundResource(R.drawable.blue_button_shape);
						btSend.setEnabled(true);
						
				}
				
				if(campoMonto.getText().toString().equals(".") ){
					campoMonto.setText("0.");
					campoMonto.setSelection(2);
					flagMonto=true;
					btSend.setBackgroundResource(R.drawable.button_disable_shape);
					//itemMenu.setEnabled(false);
					btSend.setEnabled(false);
				}
				
				if(!campoMonto.getText().toString().isEmpty()){
					campoMonto.setFilters(new InputFilter[]{filter});
					
					if(campoMonto.length() == 1){
						campoMonto.setText(campoMonto.getText().toString() + ".00");
						campoMonto.setSelection(1);
						flagMonto=true;
					}
					
					setMonto( Float.parseFloat(campoMonto.getText().toString()));					
				}else{
					setMonto( 0 );
					setCleanMountField();
				}
				total = getMonto() + extra;
				

				campoTotal.setText( Utils.setFloatFormat(total));
					//Float.toString(total));
			}

			@Override
			public void afterTextChanged(Editable s) {}			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}});
	
		Log.d(ConstantsValues.TAG_PAYFORM, "gps:" + gps );
		
		gps.getLocation();
		delayGPSInfo();	
	}
	
	public void delayGPSInfo(){
		if(gps.canGetLocation()){
			
			try {				
				Handler handler  =new Handler();
				handler.postDelayed(new Runnable(){

					@Override
					public void run() {
						try{
				        	latitude = gps.getLocation().getLatitude();
				        	Log.d(ConstantsValues.TAG_TAEFORM, "Lat: ["+latitude+"]");
				        	longitude = gps.getLocation().getLongitude();
				        	Log.d(ConstantsValues.TAG_TAEFORM, "Long: ["+longitude+"]");
				        	if(longitude != 0){
				        		compra.setCx(String.valueOf(longitude));
				        		compra.setCy(String.valueOf(latitude));
				        	}
				        }catch(Exception e){
				        	e.printStackTrace();
				        	compra.setCx(null);
				        }
					}
					
				},ConstantsValues.TIEMPO_ESPERA_POSICION);
				
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}else{
			gps.showSettingsAlert();
		}
	}
	
	public void showAlertMountEmpty(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(context.getString(R.string.alert_title_1));
		alert.setMessage(context.getString(R.string.alert_message_1));
		alert.setPositiveButton(context.getString(R.string.confirmation_positive), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				campoMonto.requestFocus();
			}
		});

		alert.show();
	}
	
	public void showAlertDescriptionEmpty(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(context.getString(R.string.title_alert_desc));
		alert.setMessage(context.getString(R.string.msg_alert_desc));
		alert.setPositiveButton(context.getString(R.string.confirmation_positive), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				sendPayOption();
			}
		});
		alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				campoMonto.requestFocus();
			}
		});

		alert.show();
	}
	
	public void sendPayOption(){
		compra.setMonto(Double.toString(Utils.getDoubleFormatDecimal(campoTotal.getText().toString())));
		Log.i("teclas","cantidad" + compra.getMonto() );
		compra.setProducto(descripcion.getText().toString());
	
		
		Log.d(ConstantsValues.TAG_PAYFORM, "Se coloca el objeto a pasar con datos de pago...");
		Log.d(ConstantsValues.TAG_PAYFORM, "MONTO: ["+compra.getMonto()+"]");									
		Log.d(ConstantsValues.TAG_PAYFORM, "Cx:" + compra.getCx());
		
		 if(this.monto != 0  || !(campoMonto.getText().toString().isEmpty())){
			 setGPSInfo();
		 }else{
			showAlertMountEmpty();
			Log.d(ConstantsValues.TAG_PAYFORM, "Monto vacio" );
		}
	}
	
	public void setGPSInfo(){
		 if(gps.getIsNetworkEnabled() || compra.getCx() != null){
				bundle = new Bundle();
				bundle.putSerializable("TAEtrans", compra);
				activityChange = new Intent(this, CardDataCaptureActivity.class);
				activityChange.putExtras(bundle);
				startActivity(activityChange);
			} else{
				gps.showDialogSettingGPS();
				//status = gps.getFlag();
				Log.d(ConstantsValues.TAG_PAYFORM, "MontoGPS:" + compra.getCx());
				//Log.d(ConstantsValues.TAG_PAYFORM, "status2:" + status );
				Log.d(ConstantsValues.TAG_PAYFORM, "status2 <flag:" + gps.getFlag() );
			}
	}
	
	
	public void setCleanMountField(){
		campoMonto.setHint(R.string.hint_monto);
		campoMonto.requestFocus();
		btSend.setBackgroundResource(R.drawable.button_disable_shape);
		btSend.setEnabled(false);
		flagMonto=true;
		//itemMenu.setEnabled(false);
	}
	/*
	 * Method in order to clean form
	 * */
	public void setCleanForm(){
		campoMonto.setHint(R.string.hint_monto);
		campoMonto.setText("");
		campoMonto.requestFocus();
		campoExtra.setHint(R.string.hint_extras);
		campoExtra.setText("");
		campoTotal.setText("0.00");
		descripcion.setHint(R.string.text_descripcionDummy);
		btSend.setBackgroundResource(R.drawable.button_disable_shape);
		btSend.setEnabled(false);
		flagMonto=true;
		flagExtra=true;
		//itemMenu.setEnabled(false);
	}

}//end class

